package com.utf999.qiangmanger.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.utf999.qiangmanger.entity.JsonEntity;
import com.utf999.qiangmanger.utils.JSONUtils;
/**
 * 所有controller的父级类，里面的工具方法可以是开发人员轻松的构建control层的代码。特别是基于json格式的http接口
 * @author yinwenjie
 *
 */
public class BaseController {
	/**
	 * 日志信息
	 */
	private static Log LogBaseController = LogFactory.getLog(BaseController.class);
	
	/**
	 * 获得登陆者对应的token信息。<br>
	 * 注意,如果没有登录或者没有token信息，则返回null
	 * @param request
	 * @return
	 */
	protected String getToken(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String token = null;
		for(int index = 0 ; cookies != null && index < cookies.length ; index++) {
			Cookie cookie = cookies[index];
			if(StringUtils.equals(cookie.getName(), "token")) {
				token = cookie.getValue();
			}
		}
		
		return token;
	}
	
	/**
	 * 将token信息写入cookies
	 * @param request
	 */
	protected void writeToken(HttpServletResponse response , String token) {
		Cookie cookie = new Cookie("token", token);
		response.addCookie(cookie);
	}
	
	/**
	 * 将token信息清除掉
	 * @param response
	 */
	protected void unwriteToken(HttpServletResponse response) {
		Cookie cookie = new Cookie("token", "");
		response.addCookie(cookie);
	}
	
	/**
	 * 向response中写入字符串,一般返回错误信息的时候，会使用该打印方法
	 * @param response HttpServletResponse
	 * @param msg 写入的字符串
	 */
	protected void writeResponseMsg(HttpServletResponse response, JsonEntity jsonEntity) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (Exception e) {
			BaseController.LogBaseController.error(e.getMessage(), e);
		}
		
		String jsonstr = JSONUtils.toString(jsonEntity); 
		out.print(jsonstr);
	}
	
	/**
	 * 向response中写入字符串,一般返回错误信息的时候，会使用该打印方法
	 * @param response HttpServletResponse
	 * @param jsonEntity 
	 * @param filterProperties 需要进行过滤的，即不进行页面显示的json属性
	 * @throws IOException
	 */
	protected void writeResponseMsg(HttpServletResponse response, JsonEntity jsonEntity , String... filterProperties) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			BaseController.LogBaseController.error(e.getMessage(), e);
		}
		
		String jsonstr = JSONUtils.toString(jsonEntity , filterProperties); 
		out.print(jsonstr);
	}
}
